<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 放置页签 -->
          <el-tab-pane label="角色管理">
            <!-- 新增角色按钮 -->
            <el-row style="height: 60px">
              <el-button
                icon="el-icon-plus"
                size="small"
                type="primary"
                @click="handleOpen('新增角色')"
              >新增角色</el-button>
            </el-row>
            <!-- 表格 -->
            <el-table :data="roleList" border="">
              <el-table-column prop="name" label="角色名称" width="240" />
              <el-table-column prop="description" label="描述" />
              <el-table-column label="操作">
                <template v-slot="{row}">
                  <el-button size="small" type="success" @click="showPermission(row.id)">分配权限</el-button>
                  <el-button
                    size="small"
                    type="primary"
                    @click="getRole(row.id)"
                  >编辑</el-button>
                  <el-button size="small" type="danger" @click="del(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页组件 -->
            <el-row
              type="flex"
              justify="center"
              align="middle"
              style="height: 60px"
            >
              <!-- 分页组件 -->
              <el-pagination
                layout="prev, pager, next"
                :total="total"
                :current-page="currentPage"
                :page-size="pageConfig.pagesize"
                @current-change="currentChange"
                @prev-click="changeList('prev')"
                @next-click="changeList('next')"
              />
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="公司信息">
            <el-form label-width="120px" style="margin-top: 50px">
              <el-form-item label="公司名称">
                <el-input
                  v-model="companyData.name"
                  disabled
                  style="width: 400px"
                />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input
                  v-model="companyData.companyAddress"
                  disabled
                  style="width: 400px"
                />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input
                  v-model="companyData.mailbox"
                  disabled
                  style="width: 400px"
                />
              </el-form-item>
              <el-form-item label="备注">
                <el-input
                  v-model="companyData.remarks"
                  type="textarea"
                  :rows="3"
                  disabled
                  style="width: 400px"
                />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <!-- 弹框 -->
      <el-dialog
        :title="title"
        :visible="dialogVisible"
        width="50%"
        :before-close="handleClose"
      >
        <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="120px">
          <el-form-item label="员工名称" prop="name">
            <el-input v-model="roleForm.name" />
          </el-form-item>
          <el-form-item label="员工描述" prop="description">
            <el-input v-model="roleForm.description" />
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button
            type="primary"
            @click="submit"
          >确 定</el-button>
        </span>
      </el-dialog>
      <!-- 设置角色权限弹窗 -->
      <el-dialog title="分配权限" :visible="isShowPermission" @close="btnPermCancel">
        <!-- data 是数据数组, 套着一堆对象 props 指定要显示的字段,
        default-expand-all 默认展开所有 -->
        <el-checkbox-group v-model="checkList">
          <!-- 本来多个多选框需要自己 v-for 遍历, 但是这里由树形处理了 -->

          <!-- 每个属性节点都是一个多选框 -->
          <!-- <el-checkbox v-for="item in permList" :key="item.id" :label="item.id">
            {{ item.name }}
          </el-checkbox> -->
          <el-tree :data="permList" default-expand-all>
            <template v-slot="scope">
              <el-checkbox :label="scope.data.id">
                {{ scope.data.name }}
              </el-checkbox>
            </template>
          </el-tree>
        </el-checkbox-group>
        <template #footer>
          <el-button size="small" type="primary" @click="btnPermOK">确定</el-button>
          <el-button size="small" @click="btnPermCancel">取消</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { getPermissionList } from '@/api/permisson'
import { getCompanyById, getAllrole, getRolebyId, delRolebyId, updateRole, addRole, assignPerm } from '@/api/user'
import { listToTree } from '@/utils'
export default {
  name: 'Settings',
  data() {
    return {
      companyData: {},
      dialogVisible: false,
      total: 10,
      pageConfig: {
        page: 1,
        pagesize: 10
      },
      roleList: [],
      currentPage: 1,
      roleForm: {
        name: '',
        description: ' '
      },
      title: '',
      rules: {
        name: { required: true, message: '该项不能为空', trigger: 'blur' },
        description: { required: true, message: '该项不能为空', trigger: 'blur' }
      },
      id: 0,
      // 设置权限相关
      isShowPermission: false,
      // 所有权限数组
      permList: [],
      // 被选中的权限数组
      checkList: [],
      roleId: ''

    }
  },
  computed: {
    ...mapState('user', ['userInfo'])
  },
  async created() {
    const res = await getCompanyById(this.userInfo.companyId)
    this.companyData = res.data
    await this.setRole()
    // 获取权限列表
    const result = await getPermissionList()
    console.log('权限列表', result.data)
    this.permList = listToTree(result.data, '0')
  },
  methods: {
    // 权限设置相关
    async  showPermission(id) {
      // 获取角色旧数据, 回显多选框
      const { data } = await getRolebyId(id)
      this.checkList = data.permIds
      console.log(data.permIds)
      console.log(data)
      this.roleId = id
      this.isShowPermission = true
    },
    async btnPermOK() {
      await assignPerm({
        id: this.roleId,
        permIds: this.checkList
      })
      this.$message.success('修改成功')
      this.isShowPermission = false
    },
    btnPermCancel() {
      this.isShowPermission = false
    },
    // 增加减少
    changeList(value) {
      if (value === 'prev') {
        this.page++
      } else if (value === 'next') {
        this.page--
      }
      this.setRole()
    },
    // 获取员工列表
    async setRole() {
      const result = await getAllrole(this.pageConfig)
      this.roleList = result.data.rows
      this.total = result.data.total
      // if (result.data.rows.length < 1 && this.pageConfig.page > 1) {
      //   this.pageConfig.page--
      //   await this.setRole()
      // }
    },
    // 点击页码
    async currentChange(newpage) {
      this.pageConfig.page = newpage
      await this.setRole()
    },
    // 打开弹窗
    handleOpen(title) {
      this.id = ''
      this.title = title
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.roleForm.resetFields()
        // this.roleForm = this.$options.data().roleForm // 重置data中的 某个form表单
      })
    },
    // 关闭弹窗
    handleClose() {
      this.dialogVisible = false
    },
    // 获取单个员工的数据
    async getRole(id) {
      this.handleOpen('修改角色')
      this.id = id
      const res = await getRolebyId(id)
      for (const key in res.data) {
        if (!(this.roleForm[key] === undefined)) {
          this.roleForm[key] = res.data[key]
        }
      }
    },
    // 删除角色
    async del(id) {
      try {
        await this.$confirm('你确认要删除吗？')
        await delRolebyId(id)
        this.$message.success('删除成功啦')
        await this.setRole()
      } catch (error) {
        this.$message.warning('取消删除')
      }
    },
    // 提交数据
    async submit() {
      try {
        await this.$refs.roleForm.validate()
        let flag = false
        if (this.id) {
          await updateRole(this.id, this.roleForm)
        } else {
          flag = true
          await addRole(this.roleForm)
        }
        this.$message.success('操作成功')
        this.handleClose()
        if (flag) {
          await this.currentChange(this.currentPage = Math.ceil(this.total / this.pageConfig.pagesize))
        } else {
          this.setRole()
        }
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>

<style>
</style>
